/* global expect */

const fs = require('fs')
const axios = require('axios')
global.expect = require('chai').expect
const Cookie = require('simple-cookie')
const config = require('../config/local.env.js')
const querystring = require('querystring')
let apiHost = JSON.parse(config.BASE_API)
const lastArgv = process.argv[process.argv.length - 1]
if (lastArgv.indexOf('://') !== -1) {
  apiHost = lastArgv
}

const apiTest = function() {}

// 合并公共请求参数
apiTest.unitGet = function(uri, o) {
  if (uri.substr(0, 5) === '/api/') return Object.assign({ appid: '123', secret: '123' }, o || {})
  return Object.assign({ token: apiTest.getToken() }, o || {})
}

apiTest.get = function(uri, data) {
  return axios.get(apiHost + uri, { params: apiTest.unitGet(uri, data) })
}

apiTest.post = function(uri, data, type) {
  type = type || 'json'
  if (uri.indexOf('?') === -1) uri += '?'
  else uri += '&'
  // console.log(apiHost + uri)
  var url = apiHost + uri + 'token=' + apiTest.getToken()
  if (uri.substr(0, 5) === '/api/') {
    url = apiHost + uri + 'appid=5a97c26c9c950c6cd736e640&secret=24b89ed6ef4e6d63d6dd6823a4931d102868ddc3486f80e9f2a6f1cd0d755f45'
  }
  if (type === 'json') return axios.post(url, data)
  return axios.post(url, querystring.stringify(data))
}

// 获取token
apiTest.getToken = function() {
  return fs.readFileSync('test/token', { encoding: 'utf8' })
}

// 获取token
apiTest.getCookies = function(res) {
  var arr = []
  expect(res.headers['set-cookie']).to.be.an('array')
  res.headers['set-cookie'].forEach(function(v) {
    var cookie = Cookie.parse(v)
    arr.push(cookie)
  })
  return arr
}

// 获取token
apiTest.getCookie = function(res) {
  var o = {}
  expect(res.headers['set-cookie']).to.be.an('array')
  res.headers['set-cookie'].forEach(function(v) {
    var cookie = Cookie.parse(v)
    o[cookie.name] = cookie.name
  })
  return o
}

// 获取正常请求对象
apiTest.apiOk = function(res) {
  var json = res.data
  expect(json).to.be.an('object')
  expect(json.code).to.equal(30000, '接口返回错误码' + JSON.stringify(json))
  expect(json).to.have.property('data')
  expect(json).to.not.have.property('error')
  expect(json.data).to.be.a('object')
  return json.data
}

// 获取错误请求对象
apiTest.apiErr = function(res, code) {
  var json = res.data
  expect(json).to.be.an('object')
  expect(json.code).to.be.a('number').to.not.equal(30000, JSON.stringify(json))
  if (code) expect(json.code).to.equal(code)
  if (json.error) {
    expect(json).to.have.property('error').to.be.a('object')
    expect(json.error).to.be.ok
    return json.error
  }
  // expect(json).to.not.have.property('data')
  // console.log(json)
  return json
}

// 分页判断
apiTest.checkPaging = function(data, get) {
  expect(data.total).to.be.a('number')
  expect(data.page).to.be.a('number')
  expect(data.limit).to.be.a('number')
  expect(data.list).to.be.an('array')
  // 分页条数验证
  expect(data.list.length).to.be.at.most(data.limit)
  if (get) {
    if (get.page) expect(data.page).to.equal(get.page)
    get.page = get.page || 1
    var size = get.page * get.limit
    var realsize = get.limit
    if (get.limit) {
      if (size > data.total) realsize = data.total - size + get.limit
      if (realsize < 0) realsize = 0
      expect(data.list.length).to.equal(realsize)
      // console.log(data.total, data.list.length, realsize)
    }
  }
}

apiTest.isObjectId = function(str) {
  expect(str).to.match(/^[0-9a-f]{24}$/)
}

apiTest.isIp = function(str) {
  expect(str).to.match(/^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/)
}

apiTest.random = function(min, max) {
  var dx = max - min
  var Rand = Math.random()
  var num = min + Math.round(Rand * dx) // 四舍五入
  return num
}

// 随机取数组中的n个
apiTest.ranArr = function(arr, min, max) {
  var arrs = Object.assign([], arr)
  var num = min
  if (max) num = apiTest.random(min, max)
  var nrr = []
  for (var i = 0; i < num; i++) {
    var pid = apiTest.random(0, arrs.length - 1)
    nrr.push(arrs[pid])
    arrs.splice(pid, 1)
  }
  return nrr
}

global.apiTest = apiTest
module.exports = apiTest
